package cn.ococci.dm.Main.Activity;

import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.SystemClock;
import android.support.v4.app.FragmentTransaction;

import com.umeng.update.UmengUpdateAgent;

import java.util.List;

import cn.ococci.dm.Base.BaseActivity;
import cn.ococci.dm.Base.BaseFragment;
import cn.ococci.dm.Base.FragmentController;
import cn.ococci.dm.Main.Const;
import cn.ococci.dm.Main.DoorBiz;
import cn.ococci.dm.Main.Fragment.HomeFragment;
import cn.ococci.dm.Main.Fragment.ModifyDoorFragment;
import cn.ococci.dm.Main.Model.CurUser;
import cn.ococci.dm.Main.Model.DoorModel;
import cn.ococci.dm.Main.Model.DoorUnitModel;
import cn.ococci.dm.Main.Model.UnitModel;
import cn.ococci.dm.Main.Tools.DbTool;
import cn.ococci.dm.Main.Tools.FileTool;
import cn.ococci.dm.Main.Tools.LogTool;
import cn.ococci.dm.Main.Tools.SpTool;
import cn.ococci.dm.Main.Tools.ThreadTool;
import cn.ococci.dm.Network.HttpCallback;
import cn.ococci.dm.WiFi.ScanWiFiBroadcastReceiver;
import cn.ococci.dm.WiFi.WifiOperate;
import cn.ococci_dm.R;

/**
 * Created by cyan on 15/12/29.
 *  控制器,界面的替换,网络,广播监听以及初始化公共数据，同步数据
 */
public class MainActivity extends BaseActivity implements FragmentController {

    public BaseFragment curFragment;

    private ScanWiFiBroadcastReceiver scanWifiBroadcastReceiver;

    public WifiOperate operate;

    @Override
    protected int getResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {}

    @Override
    protected void initData() {
        CurUser.init();
        FileTool.deleteDirectory();
        DoorBiz.getOtaVersionListInfo(this);

        operate = new WifiOperate(this);
        this.setFragment(-1);

        initNeedData();

        initScanWiFi();

        synUnitListData();

        UmengUpdateAgent.update(this);

    }

    private void initNeedData(){

        DoorBiz.getFloorList(new HttpCallback<UnitModel>() {});

        if (operate.isWifiConnected()){
            SpTool.putString(Const.LoginParams.LOGIN_NET_NAME,operate.returnWifiBSsId());
        }

    }


    public synchronized  void initScanWiFi(){

        if (scanWifiBroadcastReceiver == null) {

            scanWifiBroadcastReceiver = new ScanWiFiBroadcastReceiver(operate.getWifiManager(), new HttpCallback<ScanResult>() {
                @Override
                public void onSuccessList(List<ScanResult> scanResultList) {

                    LogTool.log(LogTool.CYAN,"扫描到的数据个数:"+scanResultList.size());

                    for (ScanResult result : scanResultList){

                        LogTool.log(LogTool.CYAN,""+result.SSID + " ->" + result.BSSID);
                    }


                    if (curFragment instanceof HomeFragment){

                        ((HomeFragment) curFragment).refreshListView(scanResultList);
                    }

                    if (curFragment instanceof ModifyDoorFragment){

                        ((ModifyDoorFragment) curFragment).refreshListView(scanResultList);
                    }

                }
            });
        }

        registerReceiver(scanWifiBroadcastReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        operate.startScan();
    }



    private void synUnitListData(){

        DoorBiz.uploadDeviceRoundWifi(DbTool.findAllNoUploadsWifiObjData());

        ThreadTool.runOnNewThread(new Runnable() {
            @Override
            public void run() {

                List<DoorModel> doorModelList  = DbTool.findAllDoor();

                if(!doorModelList.isEmpty()){
                    for(DoorModel dm :doorModelList){

                        List<DoorUnitModel> dum  = DbTool.findDoorUnitListWithNeedSyn(dm.getDoorId());

                        if(!dum.isEmpty()){
                            DoorBiz.setDoorPermission(true, dm.getDoorId(), dum, new HttpCallback() {
                                @Override
                                public void onSuccess(Object data) {

                                }
                            });
                            SystemClock.sleep(200);
                        }

                    }
                }
            }
        });

    }


    private void setFragment(int animType) {
        if (curFragment == null ) {
            this.setFragment(new HomeFragment(), animType);
        }
    }



    public synchronized void setFragment(BaseFragment fragment, int animType) {

        if (fragment.getActivity() != null) {
            return;
        }
        FragmentTransaction ft = this.obtainFragmentTransaction(animType);
        if (curFragment != null) {
            ft.remove(curFragment);
        }
        curFragment = fragment;
        ft.replace(R.id.fragmentContainer, curFragment);
        ft.disallowAddToBackStack();
        ft.commitAllowingStateLoss();

    }



    private FragmentTransaction obtainFragmentTransaction(int animType) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        switch (animType) {
            case Const.ANIM_NEXT:
                ft.setCustomAnimations(R.anim.activity_gonext_enter_anim,
                        R.anim.activity_gonext_exit_anim);
                break;
            case Const.ANIM_BACK:
                ft.setCustomAnimations(R.anim.activity_goback_enter_anim,
                        R.anim.activity_goback_exit_anim);
                break;
        }

        return ft;
    }


    @Override
    public boolean goBack() {
        return this.curFragment.goBack();
    }

    @Override
    protected void onDestroy() {

        if (scanWifiBroadcastReceiver != null){
            unregisterReceiver(scanWifiBroadcastReceiver);
            scanWifiBroadcastReceiver = null;
        }

        super.onDestroy();

    }
}
